package com.caiyigo.baihua.controller;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.caiyigo.baihua.dto.Result;
import com.caiyigo.baihua.model.SystemBug;
import com.caiyigo.baihua.service.BugService;
@ControllerAdvice
public class ExceptionControllerAdvice {
	@Resource
	BugService bugService;

	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public Result exception(Exception e) {
		bugService.insertSelective(new SystemBug("系统错误", 1, new Date(),
				new Date(), getErrorInfoFromException(e)));
		return new Result(false, "系统错误，操作失败!");
	}

	public static String getErrorInfoFromException(Exception e) {
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			return "\r\n" + sw.toString() + "\r\n";
		} catch (Exception e2) {
			return "bad getErrorInfoFromException";
		}
	}
}
